package com.cennavi.minemapdemo.activity.basic;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.Gravity;
import android.view.View;

import com.cennavi.minemapdemo.R;
import com.cennavi.minemapdemo.activity.BaseActivty;
import com.cennavi.minemapdemo.util.Config;
import com.cennavi.minemapdemo.util.DensityUtil;
import com.minedata.minemap.MinemapAccountManager;
import com.minedata.minemap.camera.CameraPosition;
import com.minedata.minemap.camera.CameraUpdateFactory;
import com.minedata.minemap.geometry.LatLng;
import com.minedata.minemap.map.MapView;
import com.minedata.minemap.map.MineMap;
import com.minedata.minemap.overlay.MarkerLayer;
import com.minedata.minemap.overlay.MarkerLayerOptions;
import com.minedata.minemap.overlay.PolyLineLayerOptions;

import java.lang.ref.WeakReference;

/**
 * 基础地图
 */
public class BaseMapActivity extends BaseActivty {

    //地图视图
    private MapView mapView;
    //地图操作类
    private MineMap mineMap;
    private Context mContext;
    private Thread newThread; //声明一个子线程
    private MarkerLayerOptions.MarkerItem marker; // 定位的标记点
    private MarkerLayer locationMarkerLayer;
    private float bear = 0f;


    Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
//        token：dcb383d440ba454b8d18d08f66086c5e
//        MinemapAccountManager.getInstance(this, Config.MAP_TOK, "dcb383d440ba454b8d18d08f66086c5e", Config.MAP_ID);

        MinemapAccountManager.getInstance(this, Config.MAP_TOK, Config.OFFLINE_TOK, Config.MAP_ID);
        setContentView(R.layout.activity_map_base);
        mapView = findViewById(R.id.mapview);
        mapView.onCreate(savedInstanceState);
        //初始化地图
        initMap();

        newThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        if (marker != null)
                            marker.iconRotate(bear);
                        mHandler.sendEmptyMessage(TRFFICFLAG);
                        Thread.sleep(100);
                        bear = bear + 10.0f;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        break;
                    }
                }
            }
        });
        mHandler = new MyHandler(this);
        newThread.start();


    }
    //生命周期
    @Override
    protected void onStart() {
        super.onStart();
        if (mapView != null)
            mapView.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mapView != null)
            mapView.onStop();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mapView != null)
            mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mapView != null)
            mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //2.0.6及之后版本 需要将加入地图的图片资源进行清理
        if (mineMap != null)
            mineMap.removeImagesAll();


        if (mapView != null)
            mapView.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        if (mapView != null){
            mapView.onLowMemory();
        }
    }

    private MyHandler mHandler;
    //刷新路况的标识
    private static final int TRFFICFLAG = 1111;

    private class MyHandler extends Handler {
        private WeakReference<BaseMapActivity> activityWeakReference;

        public MyHandler(BaseMapActivity activity) {
            activityWeakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            BaseMapActivity activity = activityWeakReference.get();
            if (    activity != null) {
                switch (msg.what) {
                    case TRFFICFLAG:
                        if (locationMarkerLayer != null&& locationMarkerLayer.isLayerExist())
                            locationMarkerLayer.update();
                        break;
                }
            }
        }
    }

    public void zoomIn(View view) {
        if (mineMap != null) {
            mineMap.moveCamera(CameraUpdateFactory.zoomIn());
        }
    }

    public void zoomOut(View view) {
        if (mineMap != null) {
            mineMap.moveCamera(CameraUpdateFactory.zoomOut());
        }
    }

    private void initMap() {

        //mine map sdk 2.0.6之前生效
        // mapView.setStyleUrl(Config.mBaseUrl + Config.MAP_ID);

        mapView.addMapRenderCallback(new MapView.OnMapReadyListener() {
            @Override
            public void onMapReady(MineMap oMineMap) {
                mineMap = oMineMap;
                mineMap.getUiSettings().setZoomControlsEnabled(false);
                mineMap.getUiSettings().setRotateGesturesEnabled(true);// 是否可以旋转地图
                mineMap.getUiSettings().setTiltGesturesEnabled(true);
                mineMap.setStyleUrl(Config.mBaseUrl + Config.MAP_ID, new MineMap.OnStyleLoadedListener() {
                    @Override
                    public void onStyleLoaded(String s) {

                        //mine map sdk 2.0.6及之后版本这样使用
                        addImageToMap();

                    }
                });
                //设置指南针是否显示，默认是显示
                mineMap.getUiSettings().setCompassEnabled(true);
                mineMap.getUiSettings().setCompassGravity(Gravity.LEFT);
//                mineMap.getUiSettings().setCompassImage(getResources().getDrawable(R.mipmap.icon_compass));
                mineMap.getUiSettings().setCompassMargins(DensityUtil.dip2px(mContext, 11), DensityUtil.dip2px(mContext, 80),
                        0, 0);
                mineMap.setCameraPosition(
//                        new CameraPosition.Builder().target(new LatLng(32.01627, 118.87309))
                        new CameraPosition.Builder().target(new LatLng(33.350036, 120.157288))
                                .zoom(14)
                                .tilt(0)//设定倾斜角度
                                .bearing(0) //摄像机指向的方向,从北部顺时针方向设置
                                .build());
                mineMap.setMaxZoomPreference(17);//设置最高展示级别，最高为17级别
                mineMap.setMinZoomPreference(3);//设置最低的展示级别

                marker = new MarkerLayerOptions.MarkerItem().icon(R.drawable.ic_arrow+"").position(new LatLng(32.01627, 118.87309));
                MarkerLayerOptions Layer = new MarkerLayerOptions("locationMarkerLayer")
                        .iconAnchor(MarkerLayerOptions.ANCHOR_CENTER)//基准点
                        .iconPitchAlignment(MarkerLayerOptions.PITCH_ALIGNMENT_MAP);
                Layer.add(marker);
                locationMarkerLayer = mineMap.addLayer(Layer);
//                newThread.start(); //启动线程
//                mineMap.setTrafficShow(true);
            }
        });
    }

    //加载可能的图片资源
    private void addImageToMap() {

        Bitmap icon = drawableToBitmap(this, R.drawable.ic_arrow);
        mineMap.addImage(R.drawable.ic_arrow + "", icon);

    }


    /**
     * drawable 需要用这个方法转成 Bitmap
     * @param context
     * @param vectorDrawableId
     * @return
     */
    public static Bitmap drawableToBitmap(Context context, int vectorDrawableId) {
        Bitmap bitmap = null;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            Drawable vectorDrawable = context.getDrawable(vectorDrawableId);
            if (vectorDrawable != null) {
                bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(),
                        vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_4444);
                Canvas canvas = new Canvas(bitmap);
                vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
                vectorDrawable.draw(canvas);
            }
        } else {
            bitmap = BitmapFactory.decodeResource(context.getResources(), vectorDrawableId);
        }
        return bitmap;
    }
}
